<template>
    <div id="cart">
        <van-nav-bar
        title="购物车"
        left-text="返回"
        left-arrow
        @click-left="onClickLeft"
        />
        <!-- 主体内容 -->
            <van-checkbox-group v-model="checkedResult" @change="checkedResultChange">
                <div class="cart" v-for="item in cart" :key="item.id">
                    <van-checkbox :name="item.id"></van-checkbox>
                    <van-swipe-cell> 
                        <van-card
                        :price="item.total"
                        :title="item.product.name"
                        :desc="'库存:'+item.product.stock+item.product.unit_text"
                        class="goods-card"
                        :thumb="item.product.thumbs_text"
                        @click-thumb="clickThumb(item.product.id)"
                        >
                        <template #tags>
                            <div style="color: #969799">单价: {{ item.price }}</div>
                        </template>
                        <template #num>
                            <van-stepper @overlimit="limit" @change="numAdd(item)" :max="item.product.stock" v-model="item.nums" theme="round" button-size="22" disable-input />
                        </template>
                        </van-card>
                        <template #right>
                            <van-button @click="deleteItem(item.id)" square text="删除" type="danger" class="delete-button" />
                        </template>
                    </van-swipe-cell>
                </div>
               
            </van-checkbox-group>
        <!-- 提交订单栏 -->
        <van-submit-bar :disabled="checkedResult.length?false:true" :price="total" button-text="生成订单" @submit="onSubmit">
            <van-checkbox v-model="isCheckAll"  @click="checkAllChange">全选</van-checkbox>
        </van-submit-bar>
        <!-- 底部导航 -->
        <tabbar />
    </div>
</template>

<script setup>
    import tabbar from '@/components/tabbar.vue'
    import { computed, getCurrentInstance, onBeforeMount, onMounted } from 'vue';
    const onClickLeft = () => history.back();

    const onSubmit = async () => {
        proxy.$dialog({
            title:"提醒",
            message:"确认要生成订单吗？"
        }).then(()=>{
            proxy.$router.push({
                path:"/cart/getOrder",
                query:{id:checkedResult.value.join(","),total:total.value}
            })
        }).catch(()=>{

        })
    };

    onBeforeMount(()=>{
        getData()
    })

    // 获取购物车数据
    const {proxy} = getCurrentInstance();
    const userInfo  = proxy.$cookies.get("business")?proxy.$cookies.get("business"):{}
    const cart = ref([])
    const getData =  async () => {
        if(!userInfo.id){
            return false
        }
        let data = {
            busid:userInfo.id
        }
        let result = await proxy.$POST({
            url:"/cart/index",
            params:data,
        })
        if(result.code){
            cart.value = result.data
            result.data.forEach(item=>{
                list.value.push(item.id)
            })
            return false
        }else{
            proxy.$fail(result.msg);
            return false
        }
    }

    // 全选方法
    const list = ref([])
    const isCheckAll = ref(false);
    const checkedResult = ref([]);

    const checkAllChange = () => {
      checkedResult.value = isCheckAll.value ? list.value : []
    }


    const checkedResultChange = (value) => {
      const checkedCount = value.length
      isCheckAll.value = checkedCount === list.value.length
    }
    
    // 增加商品数量
    // 截流标志
    let flag = false
    const numAdd = async (item) => {
        if(flag){
            return false
        }
        flag = true
        let data = {
            id:item.id,
            busid:userInfo.id,
            nums:item.nums
        }
        let result = await proxy.$POST({
            url:"/cart/numschange",
            params:data
        })
        if(result.code){
            getData()
            flag = false
        }else{
            proxy.$fail(result.msg)
            flag = false
        }
    }
    // 点击不可用按钮
    const limit = (value) => {
        if(value === "plus"){
            proxy.$fail("商品库存不够了");
        }
    }

    // 计算总价
    const total = computed(()=>{
        let price = 0
        cart.value.forEach(item => {
            if(checkedResult.value.includes(item.id)){
                price += parseFloat(item.total)
            }
        })
        return price*100
    })

    // 删除购物车中商品
    const deleteItem = async (id) =>{
        proxy.$dialog({
            title:"提醒",
            message:"确定要删除该商品吗?",
        }).then(async ()=>{
            let data = {
                id,
            }
            let result = await proxy.$POST({
                url:"/cart/delete",
                params:data
            })
            if(result.code){
                proxy.$success(result.msg);
                getData()
                return false
            }
        }).catch((error)=>{
            proxy.$fail(error)
        })
    }

    // 点击商品图片
    const clickThumb = (proid) => {
        proxy.$router.push({
            path:"/product/detail",
            query:{proid}
        })
    }
</script>

<style>
    ::v-deep .cart {
    display: flex;
    width: 100%;
    }
    ::v-deep .van-swipe-cell {
    width: 100%;
    }
    .delete-button {
    height: 100%;
    }

    :global(.van-submit-bar) {
    bottom: 60px;
    }

  #cart .van-submit-bar{
    margin-bottom: 60px;
  }

  #cart .cart{
    display: flex;
    align-items: center;
    background-color: var(--van-card-background);
  }

  #cart .delete-button{
    height: 100%;
  }

  #cart .van-swipe-cell{
    width:100%;
  }

  #cart .van-card{
    padding-left: 0px;
  }

  #cart .van-checkbox{
    margin:0 10px
  }
</style>